import 'package:get/get.dart';
import 'package:get/get_common/get_reset.dart';
import 'package:get_storage/get_storage.dart';
import 'package:lib_core/bridge/common_bridge.dart';
import 'package:lib_core/const/global_cst.dart';

class NetCst {
  static late final NetCst _instance = NetCst._internal();

  factory NetCst() => _instance;
  final _kv = GetStorage();
  final _envKey = 'env';
  Env env = Env.uat; // uat默认

  NetCst._internal() {
    final envName = _kv.read<String>(_envKey);
    env = Env.values.firstWhereOrNull((v) => v.name == envName) ?? Env.uat;
  }

  final envMap = {
    Env.uat: {
      'hostUrl': 'https://www.wanandroid.com/',
    },
    Env.sit: {
      'hostUrl': 'https://www.wanandroid.com/',
    },
    Env.ver: {
      'hostUrl': 'https://www.wanandroid.com/',
    },
    Env.product: {
      'hostUrl': 'https://www.wanandroid.com/',
    }
  };

  String get hostUrl => envMap[env]!['hostUrl']!;

  List<String> get hostUrlArray => envMap.values.map((e) => e['hostUrl'] as String).toList();

  List<String> get nrUrlArray => envMap.values.map((e) => e['nrUrl'] as String).toList();

  List<String> get xIoTUrlArray => envMap.values.map((e) => e['xIoTUrl'] as String).toList();

  List<String> get xSpecUrlArray => envMap.values.map((e) => e['xSpecUrl'] as String).toList();

  Future<String> getHostUrlByEnv({Env? env}) async {
    return envMap[env ?? await getEnv()]!['hostUrl']!;
  }

  Future<Env> getEnv() async {
    if (GlobalCst.isLibrary) {
      final envName = await CommonHostApi().requestEnv();
      return Env.values.firstWhereOrNull((v) => v.name == envName) ?? Env.uat;
    } else {
      return env;
    }
  }

  void switchEnv(Env env) {
    this.env = env;
    _kv.write(_envKey, env.name);
  }
}

enum Env {
  uat,
  sit,
  ver,
  product,
}

extension EnvExt on Env {
  static const labels = ["测试环境", "1", "2", "正式环境"];

  String get label => labels[index];
}
